package com.qf.openapi2204.monitor.controller;

import cn.hutool.extra.mail.MailAccount;
import cn.hutool.extra.mail.MailUtil;
import com.qf.openapi2204.common.vo.ResultVo;
import com.qf.openapi2204.monitor.feignclient.EsClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.*;

@RestController
@RequestMapping("/mo")
@Slf4j
public class MonitorController {

    @Autowired
    EsClient esClient;

    // 用于保存曾经开启过监控任务的 Future对象
    ConcurrentHashMap<String,ScheduledFuture> taskMap = new ConcurrentHashMap();

    ScheduledExecutorService pool = Executors.newScheduledThreadPool(8);

    /**
     * 开启监控任务
     * @param apiname 要监控哪个接口，例如 test16
     * @param taskinterval 多久监控一次，单位为 秒
     * @return
     */
    @GetMapping("/start/{apiname}/{taskinterval}")
    public ResultVo startMonitor(@PathVariable("apiname") String apiname,@PathVariable("taskinterval") Integer taskinterval){
        log.debug("入参为:apiname={},taskinterval={}",apiname,taskinterval);

        // 开始监控任务
        ScheduledFuture<?> scheduledFuture = pool.scheduleWithFixedDelay(new Runnable() {
            @Override
            public void run() {

                // fein调用 es模块 ，获取接口执行的平均时长
                ResultVo vo = esClient.getApiTimeCostAvg(apiname, 10);
                double avgTime = (double) vo.getData();
                // 发邮件
                System.out.println(avgTime);
                if (avgTime>100){
                    // 创建邮件账户
                    MailAccount account = new MailAccount();
                    account.setHost("smtp.163.com"); // 邮件服务器主机名
                    account.setPort(25); // 邮件服务器端口
                    account.setAuth(true); // 是否需要身份验证
                    account.setFrom("dong_jl@163.com"); // 发件人电子邮件地址
                    account.setUser("dong_jl"); // 发件人用户名
                    account.setPass("HZXGWULEWIKQZTNC"); // 发件人密码
                    // 发送邮件
                    MailUtil.send(account, "330830235@qq.com", "接口超时报警", "接口:"+apiname+",avg="+avgTime, false);

                }

            }
        }, 1, taskinterval, TimeUnit.SECONDS);

        // 保存future对象
        taskMap.put(apiname,scheduledFuture);

        ResultVo resultVo = new ResultVo(1, "ok", "任务提交成功");

        return resultVo;


    }

    @GetMapping("/cancel/{apiname}")
    public ResultVo cancalMonitor(@PathVariable("apiname") String apiname){

        ScheduledFuture scheduledFuture = taskMap.get(apiname);
        scheduledFuture.cancel(false);

        // 移除map中的 任务
        taskMap.remove(apiname);

        return new ResultVo(1, "ok", "停止任务成功");
    }


}
